package com.daxt.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultUtil;
import com.daxt.model.dto.FourADeptDto;
import com.daxt.model.dto.FourAPostDto;
import com.daxt.model.dto.FourAUserDto;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.external.RequestInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.ObjectUtils;
import org.w3c.dom.NodeList;

import java.io.IOException;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @description: http请求webservice
 * @author: lig
 * @date: 2021/11/19
 */
public class HttpWsUtil {
    static int socketTimeout = 50000;// 请求超时时间  单位毫秒
    static int connectTimeout = 50000;// 传输超时时间

    /**
     * 使用SOAP1.1发送消息
     *
     * @param postUrl    webservice地址
     * @param soapXml    发送的报文
     * @param soapAction
     * @param user       用户名
     * @param pass       密码
     * @return
     */
    public static String postSoap1_1(String postUrl, String soapXml, String soapAction, String user, String pass) {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();


        HttpPost httpPost = new HttpPost(reWriteUrl(postUrl));

        // 需要用户名密码验证
        if (StringUtils.isNotEmpty(user)) {
            httpPost.addHeader(new BasicHeader("Authorization", "Basic "
                    + Base64.encode((user + ":" + pass).getBytes())));
        }

        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();
        httpPost.setConfig(requestConfig);

        if (soapAction != null) {
            soapAction = "";
        }
        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", soapAction);
            StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                retStr = EntityUtils.toString(httpEntity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (closeableHttpClient != null)
                    closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retStr;
    }

//    /**
//     * 使用SOAP1.2发送消息
//     *
//     * @param postUrl
//     * @param soapXml
//     * @param soapAction
//     * @param user
//     * @param pass
//     * @return
//     */
//    public static String postSoap1_2(String postUrl, String soapXml, String soapAction, String user, String pass) {
//        String retStr = "";
//        // 创建HttpClientBuilder
//        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//        // HttpClient
//        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
//        HttpPost httpPost = new HttpPost(postUrl);
//
//        // 需要用户名密码验证
//        if (StringUtils.isNotEmpty(user)) {
//            httpPost.addHeader(new BasicHeader("Authorization", "Basic "
//                    + Base64.encode((user + ":" + pass).getBytes())));
//        }
//
//        // 设置请求和传输超时时间
//        RequestConfig requestConfig = RequestConfig.custom()
//                .setSocketTimeout(socketTimeout)
//                .setConnectTimeout(connectTimeout).build();
//        httpPost.setConfig(requestConfig);
//
//        if (soapAction != null) {
//            soapAction = "";
//        }
//        try {
//            httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
//            httpPost.setHeader("SOAPAction", soapAction);
//            StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
//            httpPost.setEntity(data);
//            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
//            HttpEntity httpEntity = response.getEntity();
//            if (httpEntity != null) {
//                // 打印响应内容
//                retStr = EntityUtils.toString(httpEntity, "UTF-8");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            // 释放资源
//            try {
//                if (closeableHttpClient != null)
//                    closeableHttpClient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return retStr;
//    }

    public static String reWriteUrl(String wsdlUrl) {
        if (wsdlUrl.endsWith("?wsdl")) {
            int index = wsdlUrl.indexOf("?wsdl");
            String address = wsdlUrl;
            if (index > 0) {
                address = wsdlUrl.substring(0, index);
            }
            return address;
        } else {
            return wsdlUrl;
        }
    }

    /**
     * @description: 同步用户数据
     * @author: lig
     * @date: 2021/11/23
     */
    public static RequestInfo syscUserData(RequestInfo info) {
        try {
            info.setParse("false");
            String postUrl = info.getUrl();
            String soapXml = info.getRequestStr();
            String result = postSoap1_1(postUrl, soapXml, "", null, null);
            info.setResponseStr(result);
            info.setRequestNum("1");
            info.setCreateTime(LocalDateTime.now());
            String formatStr = getWebservicesBody(result, "return");
            if (StringUtils.isNotEmpty(formatStr)) {
                //Json的解析类对象
                JSONObject object = XML.toJSONObject(formatStr);
                JSONObject obj1 = object.getJSONObject("SelAllUserResponse");
                if (!ObjectUtils.isEmpty(obj1.get("Users"))) {
                    JSONObject obj2 = obj1.getJSONObject("Users");
                    JSONArray objArr = obj2.getJSONArray("User");
                    List<FourAUserDto> users = JSONUtil.toList(objArr, FourAUserDto.class);
                    info.setParseStr(users);
                    info.setParse("true");
                }

            }
        } catch (Exception e) {
            System.err.println("syscUserData 解析json异常");
        }
        return info;

    }
//    /**
//     * @param batch  分批次查询的查询批次
//     * @param number 每个批次返回的条数（最后一批按实际返回,如果查询结果为空，则查询完毕）
//     * @description: 同步用户数据
//     * @author: lig
//     * @date: 2021/11/23
//     */
//    public static List<FourAUserDto> syscUserData(String batch, String number) {
//        List<FourAUserDto> users = new ArrayList<>();
//        String postUrl = "http://www.sxlq.com:4572/lq4a_queryuser?wsdl";
//        String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
//                "<soapenv:Body>\n" +
//                "<selAllUser xmlns=\"http://service.sx4a.dhcc.com/\">\n" +
//                "<arg0 xmlns=\"\">&lt;SelAllUserRequest&gt;&lt;uid&gt;all&lt;/uid&gt;&lt;batch&gt;" + batch + "&lt;/batch&gt;&lt;number&gt;" + number + "&lt;/number&gt;&lt;/SelAllUserRequest&gt;\n" +
//                "</arg0>\n" +
//                "</selAllUser>\n" +
//                "</soapenv:Body>\n" +
//                "</soapenv:Envelope>";
//        String result = postSoap1_1(postUrl, soapXml, "", null, null);
//        String formatStr = getWebservicesBody(result, "return");
//        if (StringUtils.isNotEmpty(formatStr)) {
//
//            try {
//                //Json的解析类对象
//                JSONObject object = XML.toJSONObject(formatStr);
//                JSONObject obj1 = object.getJSONObject("SelAllUserResponse");
//                if (!ObjectUtils.isEmpty(obj1.get("Users"))) {
//                    JSONObject obj2 = obj1.getJSONObject("Users");
//                    JSONArray objArr = obj2.getJSONArray("User");
//                    users = JSONUtil.toList(objArr, FourAUserDto.class);
//                }
//            } catch (Exception e) {
//                System.err.println("syscUserData 解析json异常：batch：" + batch + ",number:" + number);
//            }
//        }
//        return users;
//
//    }

    /**
     * @description: 外部用户数据  《查找指定用户信息》
     * @author: lig
     * @date: 2021/11/23
     */

    public static FourAUserDto syscUserDataByName(String username) {
        FourAUserDto users = new FourAUserDto();
        String postUrl = "http://www.sxlq.com:4572/lq4a_queryuser?wsdl";
        String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
                "<soapenv:Body>\n" +
                "<SelUserRequest xmlns=\"http://service.sx4a.dhcc.com/\">\n" +
                "<uid xmlns=\"\">" + username + "\n" +
                "</uid>\n" +
                "</SelUserRequest>\n" +
                "</soapenv:Body>\n" +
                "</soapenv:Envelope>";
        String result = postSoap1_1(postUrl, soapXml, "", null, null);
        String formatStr = getWebservicesBody(result, "return");
        if (StringUtils.isNotEmpty(formatStr)) {

            //Json的解析类对象
            JSONObject object = XML.toJSONObject(formatStr);
            users = JSONUtil.toBean(object, FourAUserDto.class);


        }
        return users;

    }


    /**
     * @param batch  分批次查询的查询批次
     * @param number 每个批次返回的条数（最后一批按实际返回,如果查询结果为空，则查询完毕）
     * @description: 同步 部门 数据
     * @author: lig
     * @date: 2021/11/23
     */
    public static List<FourADeptDto> syscDeptData(String batch, String number) {
        List<FourADeptDto> depts = new ArrayList<>();
        String postUrl = "http://www.sxlq.com:4572/lq4a_queryorganization?wsdl";
        String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
                "<soapenv:Body>\n" +
                "<selAllOrganization xmlns=\"http://service.sx4a.dhcc.com/\">\n" +
                "<arg0 xmlns=\"\">&lt;SelAllOrganizationRequest&gt;&lt;uid&gt;all&lt;/uid&gt;&lt;batch&gt;" + batch + "&lt;/batch&gt;&lt;number&gt;" + number + "&lt;/number&gt;&lt;/SelAllOrganizationRequest&gt;\n" +
                "</arg0>\n" +
                "</selAllOrganization>\n" +
                "</soapenv:Body>\n" +
                "</soapenv:Envelope>";
        String result = postSoap1_1(postUrl, soapXml, "", null, null);
        String formatStr = getWebservicesBody(result, "return");
        if (StringUtils.isNotEmpty(formatStr)) {
            //Json的解析类对象
            try {
                //Json的解析类对象
                JSONObject object = XML.toJSONObject(formatStr);
                JSONObject obj1 = object.getJSONObject("SelAllOrganizationsResponse");
                if (!ObjectUtils.isEmpty(obj1.get("Organizations"))) {
                    JSONObject obj2 = obj1.getJSONObject("Organizations");
                    JSONArray objArr = obj2.getJSONArray("Organization");
                    depts = JSONUtil.toList(objArr, FourADeptDto.class);
                }
            } catch (Exception e) {
                System.err.println("syscDeptData 解析json异常：batch：" + batch + ",number:" + number);
            }


        }
        return depts;

    }

    /**
     * 岗位/职位
     *
     * @param batch  分批次查询的查询批次
     * @param number 每个批次返回的条数（最后一批按实际返回,如果查询结果为空，则查询完毕）
     * @description: 同步岗位数据
     * @author: lig
     * @date: 2021-12-27
     */
    public static List<FourAPostDto> syscPostData(String batch, String number) {
        List<FourAPostDto> dtos = new ArrayList<>();
        String postUrl = "http://www.sxlq.com:4572/lq4a_queryposition?wsdl";
        String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
                "<soapenv:Body>\n" +
                "<selAllPosition xmlns=\"http://service.sx4a.dhcc.com/\">\n" +
                "<arg0 xmlns=\"\">&lt;SelAllPositionRequest&gt;&lt;uid&gt;all&lt;/uid&gt;&lt;batch&gt;" + batch + "&lt;/batch&gt;&lt;number&gt;" + number + "&lt;/number&gt;&lt;/SelAllPositionRequest&gt;\n" +
                "</arg0>\n" +
                "</selAllPosition>\n" +
                "</soapenv:Body>\n" +
                "</soapenv:Envelope>";
        String result = postSoap1_1(postUrl, soapXml, "", null, null);
        String formatStr = getWebservicesBody(result, "return");
        if (StringUtils.isNotEmpty(formatStr)) {

            try {
                //Json的解析类对象
                JSONObject object = XML.toJSONObject(formatStr);
                JSONObject obj1 = object.getJSONObject("SelAllPositionsResponse");
                if (!ObjectUtils.isEmpty(obj1.get("Positions"))) {
                    JSONObject obj2 = obj1.getJSONObject("Positions");
                    JSONArray objArr = obj2.getJSONArray("Position");
                    dtos = JSONUtil.toList(objArr, FourAPostDto.class);
                }
            } catch (Exception e) {
                System.err.println("syscUserData 解析json异常：batch：" + batch + ",number:" + number);
            }
        }
        return dtos;

    }


    /**
     * 解析webservice的返回结果
     *
     * @param str      xml内容
     * @param nodeName 需要获取的正文内容节点名
     * @return
     */
    public static String getWebservicesBody(String str, String nodeName) {
        String s = "";
        try {
            Document doc = DocumentHelper.parseText(str);

            Element rootNode = doc.getRootElement();
            Element node = rootNode.element(nodeName);

            s = node.getText();


        } catch (Exception e) {
//            e.printStackTrace();
        }
//        System.err.println("Webservices result:" + s);
        return s;
    }


    //测试
    public static void main(String args[]) {
//        String postUrl = "http://www.sxlq.com:4572/lq4a_queryuser?wsdl";
//        String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
//                "<soapenv:Body>\n" +
//                "<selAllUser xmlns=\"http://service.sx4a.dhcc.com/\">\n" +
//                "<arg0 xmlns=\"\">&lt;SelAllUserRequest&gt;&lt;uid&gt;all&lt;/uid&gt;&lt;batch&gt;1&lt;/batch&gt;&lt;number&gt;2&lt;/number&gt;&lt;/SelAllUserRequest&gt;\n" +
//                "</arg0>\n" +
//                "</selAllUser>\n" +
//                "</soapenv:Body>\n" +
//                "</soapenv:Envelope>";
////        String postUrl = "http://localhost:9080/test/services/TestWS?wsdl";
////        String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:com=\"http://com.test.other.service\">" +
////                "   <soapenv:Header/>" +
////                "   <soapenv:Body>" +
////                "      <com:testWS>" +
////                "         <name>?</name>" +
////                "      </com:testWS>" +
////                "   </soapenv:Body>" +
////                "</soapenv:Envelope>";
//
//        String username = "";
//        String password = "";
//        String result = postSoap1_1(postUrl, soapXml, "",username,password);
//        String formatStr = getWebservicesBody(result,"return");
//
//
//
//        String formatStr = "<SelAllUserResponse><Users><User><perId>1130748911847735299</perId><deptCode>LQ229B0000</deptCode><mobilePhone>17735186626</mobilePhone><email></email><deptName>国道209改线工程项目基桩检测项目部</deptName><pwd>KozDNGGE3aRHU5nVvfx4jO3xYUceHaQC</pwd><perCardId>140202198605042037</perCardId><perCode>00000E74</perCode><updatedate>2021-05-28 22:02:29</updatedate><perName>王一飞</perName><perOldName></perOldName><perType>laborContract</perType><perStatus>1</perStatus><photo></photo><sex>1</sex><workStatus>1</workStatus><waitPostStartTime></waitPostStartTime><waitPostEndTime></waitPostEndTime><birthday>1986-05-04</birthday><nation>汉</nation><perPolitical>4</perPolitical><insertPoliticalTime></insertPoliticalTime><officePhone></officePhone><wageCard>6217922551765184</wageCard><wageCardBank>浦发银行太原北大街支行</wageCardBank><loginName>wangyifei</loginName><datas>[{jobid=79, perid=1130748911847735299, enddate=2999-12-31, updatedate=2021-05-28 22:02:29.5838, positionid=14000, id=1167255644956094475, startdate=2019-08-30, primaryflag=Y, orgid=1451, status=1}]</datas><effectTime>2019-05-21 16:15:24</effectTime><failureTime>2999-12-31 23:59:59</failureTime><deptId>1451</deptId><status>1</status></User><User><perId>1130748911856123906</perId><deptCode>LQ22A60000</deptCode><mobilePhone>17636665066</mobilePhone><email></email><deptName>昔榆高速公路基桩检测项目部</deptName><pwd>Xr8OhGCus+f3bf0VZNrbbpgs9uhQeYJo</pwd><perCardId>140622198903190019</perCardId><perCode>00000E75</perCode><updatedate>2021-05-28 22:47:55</updatedate><perName>安培怀</perName><perOldName>无</perOldName><perType>laborContract</perType><perStatus>1</perStatus><photo></photo><sex>1</sex><workStatus>1</workStatus><waitPostStartTime></waitPostStartTime><waitPostEndTime></waitPostEndTime><birthday>1989-03-19</birthday><nation>汉</nation><perPolitical>4</perPolitical><insertPoliticalTime></insertPoliticalTime><officePhone></officePhone><wageCard>6217922551765192</wageCard><wageCardBank>浦发银行太原北大街支行</wageCardBank><loginName>anpeihuai</loginName><datas>[{jobid=79, perid=1130748911856123906, enddate=2999-12-31, updatedate=2021-03-04 11:48:55.92117, positionid=17751, id=1167255644956094476, startdate=2019-08-30, primaryflag=Y, orgid=1894, status=1}, {jobid=74, perid=1130748911856123906, enddate=2999-12-31, updatedate=2021-01-29 18:03:19.95497, positionid=19276, id=1355094167985848322, startdate=2021-01-29, primaryflag=N, orgid=2010, status=1}]</datas><effectTime>2019-05-21 16:15:24</effectTime><failureTime>2999-12-31 23:59:59</failureTime><deptId>1894</deptId><status>1</status></User></Users></SelAllUserResponse>";
//        //Json的解析类对象
//        JSONObject object = XML.toJSONObject(formatStr);
//        JSONObject obj1 = object.getJSONObject("SelAllUserResponse");
//        JSONObject obj2 = obj1.getJSONObject("Users");
//        JSONArray objArr = obj2.getJSONArray("User");
//        List<FourAUserDto> users = JSONUtil.toList(objArr, FourAUserDto.class);
//
//
//        System.out.println(object.toString());

//        syscUserData("800", "1000");


    }


}
